package com.vanysoft.business.data.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.vanysoft.business.data.entity.CategoryEngineer;
import com.vanysoft.business.data.entity.CategoryList;
import com.vanysoft.business.data.entity.CategoryManager;
import com.vanysoft.business.data.entity.TreeItem;
import com.vanysoft.business.data.service.CategoryEngineerService;
import com.vanysoft.business.data.service.CategoryListService;
import com.vanysoft.business.data.service.CategoryManagerService;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.framework.aop.VanySoftValidation;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.utils.JSONResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 品类层级表 前端控制器
 * </p>
 *
 * @author YangLei
 * @since 2018-07-09
 */
@Controller
@RequestMapping("/data/categoryList")
public class CategoryListController extends BaseController {

    @Autowired
    CategoryListService categoryListService;
    @Autowired
    CategoryManagerService categoryManagerService;
    @Autowired
    CategoryEngineerService categoryEngineerService;

    @RequestMapping("index")
    public String index() {
        return "data/category";
    }

    /**
     * 品类保存
     *
     * @param categoryList
     * @param result
     * @param request
     * @param userInfo
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    @VanySoftValidation
    public JSONResponse save(@Valid CategoryList categoryList, BindingResult result, HttpServletRequest request, @SessionUser UserInfo userInfo) {
        //若当前Code非最高级别时则Parenr Code为必填项
        if (!"Market".equals(categoryList.getCurrentLevel()) && StringUtils.isEmpty(categoryList.getParentCode())) {
            throw new VanySoftValidationException(getMessage("hint.notnull"));
        }
        CategoryList entity = categoryListService.selectOne(new EntityWrapper<CategoryList>().eq("code", categoryList.getCode()).eq("is_enable", "1"));
        if (entity != null) {
            throw new VanySoftValidationException(getMessage("common.hint.exist"));
        }
        categoryList.setCreateTime(new Date());
        categoryList.setCreateUser(userInfo.getId());
        categoryList.setModifyUser(userInfo.getId());
        categoryList.setModifyTime(new Date());
        categoryListService.insert(categoryList);
        return new JSONResponse();
    }

    @RequestMapping("update")
    @ResponseBody
    @VanySoftValidation
    public JSONResponse update(@Valid CategoryList categoryList, BindingResult result, @SessionUser UserInfo userInfo) {
        categoryList.setModifyTime(new Date());
        categoryList.setModifyUser(userInfo.getId());
        categoryListService.updateById(categoryList);
        return new JSONResponse();
    }

    @RequestMapping("list")
    @ResponseBody
    public JSONResponse list(Page<CategoryList> page, String code, String des, String level) {
        page = categoryListService.selectPage(page, code, des, level);
        return new JSONResponse(page);
    }

    @RequestMapping("delete")
    @ResponseBody
    public JSONResponse delete(String id, HttpServletRequest request) {
        CategoryList categoryList = categoryListService.selectById(id);
        CategoryList entity = categoryListService.selectOne(new EntityWrapper<CategoryList>().eq("parent_code", categoryList.getCode()).eq("is_enable", "1"));
        if (entity != null) {
            throw new VanySoftValidationException(getMessage("category.hint.delete.child"));
        }
        if ("Category".equals(categoryList.getCurrentLevel())) {
            CategoryManager cm = categoryManagerService.selectOne(new EntityWrapper<CategoryManager>().eq("category_code", categoryList.getCode()).eq("is_enable", "1"));
            CategoryEngineer ce = categoryEngineerService.selectOne(new EntityWrapper<CategoryEngineer>().eq("category_code", categoryList.getCode()).eq("is_enable", "1"));
            if (cm != null || ce != null) {
                throw new VanySoftValidationException(getMessage("category.hint.delete.people"));
            }
            //TODO 品类信息与供应商信息存在关联关系
        }
        categoryList.setIsEnable("0");
        categoryListService.updateById(categoryList);
        return new JSONResponse();
    }

    /**
     * 查询某个层级的所有品类
     *
     * @param level
     * @return
     */
    @RequestMapping("queryByLevel")
    @ResponseBody
    public JSONResponse queryByLevel(String level) {
        List<CategoryList> list = categoryListService.selectList(new EntityWrapper<CategoryList>().eq("current_level", level).eq("is_enable", 1));
        return new JSONResponse(list);
    }

    @RequestMapping("tree")
    @ResponseBody
    public JSONResponse queryAll(String key) {
        List<CategoryList> list = categoryListService.selectAll(key);
        List<TreeItem> treeItems = buildTreeData(list, "", "0");
        return new JSONResponse(treeItems);
    }

    private List<TreeItem> buildTreeData(List<CategoryList> list, String code, String pid) {
        List<TreeItem> trees = new ArrayList<>();
        for (CategoryList categoryList : list) {
            if (pid.equals(categoryList.getPid()) && (categoryList.getParentCode() == null || code.equals(categoryList.getParentCode()))) {
                TreeItem item = new TreeItem();
                item.setLabel(categoryList.getCode() + " " + categoryList.getEnglishDescription());
                item.setChildren(buildTreeData(list, categoryList.getCode(), categoryList.getId()));
                trees.add(item);
            }
        }
        return trees;
    }


    /**
     * 标记为能力主数据
     *
     * @return
     */
    @RequestMapping("mask")
    @ResponseBody
    public JSONResponse mask(CategoryList categoryList) {
        //TODO 需将该Code信息推送至VWP，用于供应商选择注册本单位能力信息
        return new JSONResponse(categoryListService.updateById(categoryList));
    }

}

